package com.e7.service;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.e7.common.Constants;
import com.e7.dao.UserDao;
import com.e7.model.User;

@Service
public class UserService {
	private UserDao userDao = new UserDao();
	private ValidateService validater;

	/**
	 * get user with the specified account
	 * 
	 * @param account
	 *            nickName, email or phoneNum
	 * @param password
	 * @return
	 */
	public User getUserBy(String account) {
		String field = "phoneNum";
		if (!this.validater.isValidPhone(account)) {
			field = account.indexOf("@") > 0 ? "email" : "nickName";
		}
		return userDao.findOne(field, account);
	}

	public boolean register(User user) {
		if (this.userDao.save(user)) {
			return true;
		}
		return false;
	}

	@Resource
	public void setUserDAO(UserDao userDAO) {
		this.userDao = userDAO;
	}

	@Resource
	public void setValidater(ValidateService validater) {
		this.validater = validater;
	}

	public void sendPassword(String c, User user) {
		// TODO Auto-generated method stub

	}

	public Integer updateStatus(String contact) {
		int index = contact.indexOf("@");
		int state = index > 0 ? 1 : 2;
		String field = index > 0 ? "email" : "phoneNum";
		User user = this.userDao.findOne(field, contact);
		if (user == null)
			return Constants.ErrorCode.NOTEXIST;
		if ((state | user.getState()) == user.getState()) {
			return Constants.ErrorCode.EXIST;
		} else {
			try {
				user.setState(state | user.getState());
				this.userDao.update(user);
			} catch (Exception e) {
				return Constants.ErrorCode.ERROR;
			}
			return 1;
		}
	}
}
